﻿using System;
using System.Net;
using System.Linq;
using HISModels.Entities;
using System.Net.Http;
using System.Web;
using Microsoft.ApplicationServer.Http.Dispatcher;
using System.Collections.Specialized;

namespace HISRestServices.Services {

    public abstract class BaseServices : ContextWrapper, IDisposable {

        public string GetFormatRequest(HttpRequestMessage request) {
            var queryString = HttpUtility.ParseQueryString(request.RequestUri.Query);
            string format = string.Empty;
            try {
                format = queryString["format"].ToString();
            } catch {
            }
            return format;
        }

        public NameValueCollection GetQueryStringCollection(HttpRequestMessage request) {
            NameValueCollection queryString = HttpUtility.ParseQueryString(request.RequestUri.Query);
            return queryString;
        }

        public void ValidateRequest(HttpRequestMessage request) {
            if (request.Content == null) {
                HttpResponseMessage noContentResponse = new HttpResponseMessage();
                noContentResponse.StatusCode = HttpStatusCode.BadRequest;
                noContentResponse.Content = new StringContent("Expected an entity body with data but no content was found.");
                throw new HttpResponseException(noContentResponse);
            }
        }

        public RefHu Hospital {
            get {
                string code = HospitalCode;
                return AppContext.RefHus.Where(a => a.CodeBusiness == code).First();
            }

        }

        public string HospitalCode {
            get {
                return HttpContext.Current.Request.Headers["his-hospitalcode"];
            }

        }

        public string UserId {
            get {
                return HttpContext.Current.Request.Headers["his-membershipuserid"];
            }

        }

        void IDisposable.Dispose() {
            try {
                base.Dispose();
            } catch { }
        }

    }
}